/**
    Copyright (C) 2011  Alexander Vollmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.jefb.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.jefb.dao.ICommonDao;
import org.jefb.entity.RoleEntity;
import org.jefb.entity.UserEntity;
import org.jefb.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author alexej
 *
 */
@Service
public class UserService implements IUserService{
	
	@Autowired
	private ICommonDao commonDAO;

	public void setCommonDAO(ICommonDao commonDAO) {
		this.commonDAO = commonDAO;
	}

	public ICommonDao getCommonDAO() {
		return commonDAO;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public List<RoleEntity> getRoles(UserEntity entity) {
		commonDAO.refresh(entity);
		List<RoleEntity> tempList = new ArrayList<RoleEntity>();
		tempList.addAll(entity.getUserRoles());
		return tempList;
	}

	@Transactional(readOnly=false, propagation = Propagation.REQUIRED)
	public void addRole(UserEntity entity, RoleEntity roleEntity) {
		commonDAO.refresh(entity);
		commonDAO.refresh(roleEntity);
		entity.getUserRoles().add(roleEntity);
	}

	@Transactional(readOnly=false, propagation = Propagation.REQUIRED)
	public void deleteRole(UserEntity entity, RoleEntity roleEntity) {
		entity.getUserRoles().remove(roleEntity);
		commonDAO.merge(entity);
	}

	@Transactional(readOnly=false, propagation = Propagation.REQUIRED)
	public List<RoleEntity> getUnassignedRoles(UserEntity selectedEntity) {
		List<RoleEntity> unassignedPermissions = new ArrayList<RoleEntity>();
		unassignedPermissions.addAll(commonDAO.findAll(RoleEntity.class));
		for(RoleEntity role:getRoles(selectedEntity)){
			if (unassignedPermissions.contains(role)) {
				unassignedPermissions.remove(role);
			}
		}
		return unassignedPermissions;
	}
}
